// internal/handler/file_handler.go
package handler

import (
	"net/http"

	"github.com/gin-gonic/gin"

	"gdrive/internal/service"
)

type FileHandler struct {
	Service service.FileService
}

func (h *FileHandler) UploadFile(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "文件上传失败"})
		return
	}

	// userID := c.GetString("user_id") // 从 JWT 中获取
	userID := "b49bd227-4401-4e4e-b4b7-f31bc2b477d4"
	filePath := c.PostForm("path") // 虚拟路径
	if filePath == "" {
		filePath = "/" + file.Filename
	}

	// 打开文件
	src, err := file.Open()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "无法读取文件"})
		return
	}
	defer src.Close()

	// 调用服务层上传
	err = h.Service.Upload(c, userID, filePath, src, file.Size, file.Header.Get("Content-Type"))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message":  "上传成功",
		"filename": file.Filename,
		"size":     file.Size,
	})
}

func (h *FileHandler) ListFiles(c *gin.Context) {
	userID := c.GetString("user_id")
	path := c.DefaultQuery("path", "/")

	files, err := h.Service.ListFiles(c, userID, path)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"files": files})
}
